<!DOCTYPE html>
<html>
<head>
    <title>碰撞</title>
</head>

<body>
<canvas id="canvas" width="600" height="400">browser not support</canvas>
</body>
<script type="text/javascript">
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");

    var ball1 = {
        x:20,
        y:285,
        r:15,
        vx:120,
        vy:0
    }

    var ball2 = {
        x:400,
        y:285,
        r:15,
        vx:-30,
        vy:0
    }

    var balls = [];
    balls.push(ball1);
    balls.push(ball2);
    ctx.fillStyle = "#030303";
    ctx.fillRect(0,0,c.width,c.height);

    function init(){
        ctx.fillStyle = "#FFF";
        for(var t in balls){
            ctx.beginPath();
            ctx.arc(balls[t].x,balls[t].y,balls[t].r,0,Math.PI*2,true);
            ctx.closePath();
            ctx.fill();
        }
    }

    function collision_1(){
        var cycle = 20;
        var s = setInterval(function(){
            ctx.fillStyle = "rgba(0,0,0,.3)";
            ctx.fillRect(0,0,c.width,c.height);
            ctx.fillStyle = "#FFF";

            if(Math.abs(ball1.x - ball2.x) <= (ball1.r + ball2.r)){
                var tv = ball1.vx;
                ball1.vx = ball2.vx;
                ball2.vx = tv;
            }


            for(var t in balls){
                balls[t].x += balls[t].vx*cycle/1000;
                ctx.beginPath();
                ctx.arc(balls[t].x,balls[t].y,balls[t].r,0,Math.PI*2,true);
                ctx.closePath();
                ctx.fill();
            }


        },cycle);
    }

    init();
    collision_1();

</script>
</html>